package org.sith.gwt;

/*
 * Copyright 2001-2005 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

/**
 * @goal generateProxy
 * @phase compile
 * @requiresDependencyResolution compile
 */
public class ProxyGeneratorTask
        extends AbstractMojo {


    private static final String CLASS_EXT = ".class";
    /**
     * Location of the generated proxy classes
     *
     * @parameter default-value="${basedir}/src/main/java"
     */
    private File destinationDir;


    /**
     * The maven project descriptor
     *
     * @parameter expression="${project}"
     * @required
     * @readonly
     */
    private MavenProject project;


    /**
     * @parameter
     */
    private Set<String> artifactsForScan;


    /**
     * @parameter
     */
    private Set<String> classPatterns;


    /**
     * @parameter
     */
    private String destinationPackage;


    public void execute() throws MojoExecutionException {

        Map<String, Artifact> artifacts = project.getArtifactMap();


        List<URL> urls = new ArrayList<URL>();
        List<String> clazzes = new ArrayList<String>();
        for (String key : artifactsForScan) {
            if (!artifacts.containsKey(key)) {
                continue;
            }
            String absolutePath = artifacts.get(key).getFile().getAbsolutePath();
            updateClassPathUrls(urls, absolutePath);
            for (String classPattern : classPatterns) {
                try {
                    clazzes.addAll(PackageUtils.getClasseNamesInPackage(absolutePath, classPattern));
                } catch (IOException e) {
                    throw new IllegalStateException(e);
                }
            }
        }

        JarFileLoader loader = new JarFileLoader(urls.toArray(new URL[urls.size()]));
        List<Class> classList = new ArrayList<Class>();
        for (String clazzPathEntry : clazzes) {
            try {
                classList.add(loader.loadClass(clazzPathEntry));
            } catch (ClassNotFoundException e) {
                throw new IllegalStateException(e);
            }
        }

        ProxyGenerator generator = new ProxyGenerator(classList, destinationDir,destinationPackage);
        generator.generateProxy();

    }

    private void updateClassPathUrls(List<URL> urls, String absolutePath) {
        absolutePath = absolutePath.replace("\\", "/");
        String urlPath = "jar:file://" + absolutePath + "!/";
        try {
            URL url = new URL(urlPath);
            urls.add(url);
        } catch (MalformedURLException e) {
            throw new IllegalStateException(e);
        }
    }


    private void scanZip(File file) {


        /*  Class<?> aClass;
                try {
        //            loader.addFile(file.getAbsolutePath());
                    aClass = loader.loadClass("org.sith.taskrunner.ejb.db.entity.UserEntity");

                } catch (MalformedURLException e) {
                    throw new IllegalStateException(e);
                } catch (ClassNotFoundException e) {
                    throw new IllegalStateException(e);
                }
        */
        /*ZIPUtility.unzipFiles(file, temp);

    for (String path : classPatterns) {

        File targetDir = new File(temp, transformPath(path));

        *//*File[] clazzes = targetDir.listFiles(new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    return pathname.getName().endsWith(".class");
                }
            });*//*

            String[] clazzes = targetDir.list(new FilenameFilter() {

                @Override
                public boolean accept(File dir, String name) {
                    return name.endsWith(CLASS_EXT);
                }
            });

            for (String clazze : clazzes) {
                System.out.println(path+"."+clazze.replace(CLASS_EXT,""));
            }

            URL[] urls = new URL[0];
            URLClassLoader urlClassLoader = new URLClassLoader(urls);
            urlClassLoader.

        }*/
    }


    private String transformPath(String path) {
        return path.replace(".", "/");
    }

}